package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.sso.mapper.ManageMapper;
import com.tanhua.sso.pojo.Manage;
import com.tanhua.sso.utils.GetVerification;
import com.tanhua.sso.utils.ManageThreadLocal;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private GetVerification getVerification;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private ManageMapper manageMapper;
    @Value("${jwt.secret}")
    private String secret;

    /**
     * 获取验证码
     * @param uuid
     * @return
     */
    public boolean getVerification(String uuid, HttpServletRequest request, HttpServletResponse response) throws Exception{

        //1.在内存中创建一张图片
        BufferedImage bi = new BufferedImage(143, 41, BufferedImage.TYPE_INT_RGB);
        //2.得到图片
        Graphics g = bi.getGraphics();
        String verification = getVerification.getVerification(bi, g);
        //7.将随机数存在redis中
        String redisKey = "tanhua_manage_" + uuid;
        redisTemplate.opsForValue().set(redisKey, verification,300, TimeUnit.SECONDS);
        //8.设置响应头通知浏览器以图片的形式打开
        response.setContentType("image/jpeg");//等同于response.setHeader("Content-Type", "image/jpeg");
        //9.设置响应头控制浏览器不要缓存
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //10.将图片写给浏览器
        ImageIO.write(bi, "jpg", response.getOutputStream());
        return true;
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param verificationCode
     * @param uuid
     * @return
     */
    public String login(String username, String password, String verificationCode, String uuid) {
        String redisKey = "tanhua_manage_" + uuid;
        String code = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(code)){
            return null;
        }
        if (!StringUtils.equals(code,verificationCode)){
            return null;
        }

        LambdaQueryWrapper<Manage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Manage::getUsername,username);
        wrapper.eq(Manage::getPassword,password);
        Manage manage = manageMapper.selectOne(wrapper);

        //生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",manage.getUid());
        String token = Jwts.builder()
                .setClaims(claims)//存放数据,不能放置重要数据
                .signWith(SignatureAlgorithm.HS256,secret)//设置加密方法的加密盐
                .setExpiration(new DateTime().plusHours(12).toDate())//设置过期时间
                .compact();

        redisTemplate.opsForValue().set("tanhua_manage_token",token);

        return token;
    }

    /**
     * 获取信息
     * @param
     * @return
     */
    public Map<String, String> profile(Manage manage) {
        Map<String,String> map = new HashMap<>();
        map.put("uid", String.valueOf(manage.getUid()));
        map.put("username",manage.getUsername());
        map.put("avatar",manage.getAvatar());
        return map;
    }

    public Manage queryToken(String manageToken) {
        //解析token
        Map<String,Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(manageToken)
                .getBody();
        Integer id = (Integer) body.get("id");

        LambdaQueryWrapper<Manage> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Manage::getUid,id);
        Manage manage = manageMapper.selectOne(wrapper);
        return manage;

    }

}










